package me.fung.wubi.app.view.build_table

import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import me.fung.keen.app.view.View
import me.fung.keen.common.TextClipboard
import me.fung.keen.component.message.msg
import me.fung.wubi.app.component.forEachKey
import me.fung.wubi.app.component.groupColumn
import me.fung.wubi.app.component.imageVectorButton
import me.fung.wubi.app.component.mini
import me.fung.wubi.app.navigation
import me.fung.wubi.app.view.build_table.select.SelectFileDialogView
import me.fung.wubi.app.view.build_table.select.SelectFileModel
import me.fung.wubi.app.view.editor.EDITOR_VIEW

const val BUILD_TABLE_VIEW = "build_table_view"

class BuildTableView : View<BuildTablePresenter>() {
    private val dialogState: MutableState<SelectFileDialogView?> = mutableStateOf(null)

    private fun closeDialog() {
        dialogState.value = null
    }


    fun dialog(file: String, onSelect: (SelectFileModel) -> Unit) {
        dialogState.value = SelectFileDialogView(
            current = SelectFileModel(file),
            onSelected = onSelect,
            onClose = { closeDialog() },
        )
    }

    @Composable
    override fun content(modifier: Modifier) {
        val scrollState = rememberScrollState()
        val dialog: SelectFileDialogView? by remember { dialogState }
        Box(modifier.padding(3.dp)) {
            Column() {
                Column(
                    Modifier.padding(3.dp)
                        .verticalScroll(scrollState)
                ) {
                    header()
                    body()
                    Spacer(Modifier.size(35.dp))
                }
                VerticalScrollbar(ScrollbarAdapter(scrollState), modifier = Modifier.align(Alignment.End))
            }

            footer(Modifier.align(Alignment.BottomCenter).background(MaterialTheme.colors.surface))
        }
        dialog?.show(Modifier)
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun BuildTableView.header() {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Text("生成五笔码表", fontSize = MaterialTheme.typography.h6.fontSize)
        Spacer(Modifier.weight(1f))
        Button(
            onClick = { p.openSourceFolder() }, enabled = true
        ) {
            Text("打开资源目录")
        }
        Spacer(Modifier.size(3.dp))
        TooltipArea(
            tooltip = @Composable {
                Surface(
                    modifier = Modifier.shadow(4.dp),
                    color = Color(255, 255, 210),
                    shape = RoundedCornerShape(1.dp),
                ) {
                    Text(
                        text = "默认配置文件：.default",
                        modifier = Modifier.padding(10.dp)
                    )
                }
            },
            modifier = Modifier,
        ) {
            Button(
                onClick = { p.chooseConfig() }, enabled = true
            ) {
                Text("读取配置文件")
            }
        }


        Spacer(Modifier.size(3.dp))
        Button(
            onClick = { p.saveConfig() }, enabled = true
        ) {
            Text("保存配置文件")
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun BuildTableView.footer(modifier: Modifier) {
    Row(modifier) {
        TooltipArea(
            tooltip = @Composable {
                Surface(
                    modifier = Modifier.shadow(4.dp),
                    color = Color(255, 255, 210),
                    shape = RoundedCornerShape(1.dp),
                ) {
                    Text(
                        text = "格式：a 工 若 获",
                        modifier = Modifier.padding(10.dp)
                    )
                }
            },
            modifier = Modifier,
        ) {
            Button(
                onClick = {
                    p.extractTable()
                }
            ) { Text("编辑码表") }
        }
        Spacer(Modifier.weight(1f))
        Button(
            onClick = {
                p.simpleOut()
            }
        ) { Text("生成标准码表") }
        Spacer(Modifier.size(3.dp))
        Button(
            onClick = {
                p.limeOut()
            }
        ) { Text("生成冰凌码表") }
        Spacer(Modifier.size(3.dp))
        Button(
            onClick = {
                p.iBusOut()
            }
        ) { Text("生成iBus码表") }
    }
}


@Composable
private fun BuildTableView.body() {
    fileGroup(
        "字典表（全单字）（格式：aaaa 工）",
        p.model.data.lexiconFiles,
        enableEdit = false,
        enableDelete = false,
        enableClear = true,
        enableAdd = false
    )
    fileGroup(
        "词频表（格式：一个 818357166）",
        p.model.data.wordFrequencyFiles,
        enableEdit = false,
        enableDelete = false,
        enableClear = true,
        enableAdd = false
    )
    fileGroup("固定码表（格式：a 工 若 获）", p.model.data.shortCodeFiles)
    fileGroup("词组文本（格式：恭恭敬敬 花花草草 藏匿）", p.model.data.groupFiles, enableEdit = false)
    fileGroup("生僻字文本（格式：㠭）", p.model.data.rareFiles, enableEdit = false)
    buildOption(Modifier)
}

@Composable
private fun BuildTableView.buildOption(modifier: Modifier) {
    Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
        checkbox(
            checked = p.model.data.autoShort,
            text = "自动简码",
            modifier = Modifier,
            onCheckedChange = {
                p.update { copy(autoShort = it) }
            }
        )
        checkbox(
            checked = p.model.data.fullCodeOfShort,
            text = "保留简码字全码",
            modifier = Modifier,
            onCheckedChange = {
                p.update { copy(fullCodeOfShort = it) }
            }
        )
        checkbox(
            checked = p.model.data.single,
            text = "仅单字",
            modifier = Modifier,
            onCheckedChange = {
                p.update { copy(single = it) }
            }
        )
    }
}

@Composable
private fun checkbox(checked: Boolean, text: String, modifier: Modifier, onCheckedChange: (Boolean) -> Unit) {
    Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
        Checkbox(
            checked = checked,
            onCheckedChange = onCheckedChange,
        )
        Text(text = text)
    }
}

@Composable
private fun BuildTableView.fileGroup(
    title: String, fileList: MutableList<String>,
    enableSelect: Boolean = true,
    enableEdit: Boolean = true,
    enableDelete: Boolean = true,
    enableClear: Boolean = false,
    enableAdd: Boolean = true
) {
    groupColumn(
        title = title,
        modifier = Modifier.fillMaxWidth(),
    ) {
        fileList.forEachKey {
            FileItem(
                file = it,
                list = fileList,
                enableSelect = enableSelect,
                enableEdit = enableEdit,
                enableDelete = enableDelete,
                enableClear = enableClear,
            )
        }
        if (enableAdd) {
            imageVectorButton(
                tooltip = "添加", icon = Icons.Default.Add,
                modifier = Modifier.mini(),
                onClick = {
                    dialog("") {
                        fileList.add(it.file)
                        p.update { copy(version = version + 1) }
                    }
                }
            )
        }
    }
}

@Composable
private fun BuildTableView.FileItem(
    file: String,
    list: MutableList<String>,
    enableSelect: Boolean = true,
    enableEdit: Boolean = true,
    enableDelete: Boolean = true,
    enableClear: Boolean = false,
) {
    Row(
        modifier = Modifier.padding(vertical = 3.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        fileItemContent(file, Modifier.weight(1f))
        imageVectorButton(
            tooltip = "选择文件", icon = Icons.Default.ArrowDropDown, enabled = enableSelect,
            modifier = Modifier.padding(start = 3.dp).mini(),
            onClick = {
                println("选择文件: $file")
                dialog(file) {
                    val index = list.indexOf(file)
                    list[index] = it.file
                }
                p.update { copy(version = version + 1) }
            }
        )
        imageVectorButton(
            tooltip = "编辑文件", icon = Icons.Default.Edit, enabled = enableEdit,
            modifier = Modifier.padding(start = 3.dp).mini(),
            onClick = {
                navigation.goto(EDITOR_VIEW, listOf(file))
            }
        )
        imageVectorButton(
            tooltip = "复制路径", icon = Icons.Default.List, enabled = true,
            modifier = Modifier.padding(start = 3.dp).mini(),
            onClick = {
                TextClipboard.copy(file)
                msg.send { info("已复制路径到剪贴版") }
            }
        )
        imageVectorButton(
            tooltip = "移除文件", icon = Icons.Default.Delete, enabled = enableDelete,
            modifier = Modifier.padding(start = 3.dp).mini(),
            onClick = {
                list.remove(file)
                p.update { copy(version = version + 1) }
            }
        )
        imageVectorButton(
            tooltip = "清除", icon = Icons.Default.Clear, enabled = enableClear,
            modifier = Modifier.padding(start = 3.dp).mini(),
            onClick = {
                val index = list.indexOf(file)
                list[index] = ""
                p.update { copy(version = version + 1) }
            }
        )
    }
}